package com.denlaku.longan.datac;

import com.denlaku.longan.vo.DataOrigin;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author tianx
 */
public class DataSourcePool {
	private static final ConcurrentMap<String, DataSource> MAP = new ConcurrentHashMap<>();

	/**
	 * 根据数据源信息获取数据源
	 *
	 * @param dataOrigin 数据源信息
	 * @return 数据源
	 */
	public static DataSource getDataSource(DataOrigin dataOrigin) {
		String key = toKey(dataOrigin);
		DataSource dataSource = MAP.get(key);
		if (dataSource != null) {
			return dataSource;
		}
		return MAP.computeIfAbsent(key, k -> createDataSource(dataOrigin));
	}

	/**
	 * 移除数据源
	 * @param dataOrigin 数据源信息
	 */
	public static void remove(DataOrigin dataOrigin) {
		String key = toKey(dataOrigin);
		MAP.remove(key);
	}

	private static String toKey(DataOrigin dataOrigin) {
		Long tenantId = dataOrigin.getTenantId();
		String url = dataOrigin.getUrl();
		String username = dataOrigin.getUsername();
		String driverClassName = dataOrigin.getDriverClassName();
		return String.join(System.lineSeparator(), String.valueOf(tenantId), url, username, driverClassName);
	}

	private static DataSource createDataSource(DataOrigin dataOrigin) {
		HikariDataSource dataSource = new HikariDataSource();
		dataSource.setDriverClassName(dataOrigin.getDriverClassName());
		dataSource.setJdbcUrl(dataOrigin.getUrl());
		dataSource.setUsername(dataOrigin.getUsername());
		dataSource.setPassword(dataOrigin.getPassword());
		return dataSource;
	}

	private DataSourcePool() {
	}

}
